import React, { Component } from 'react';
import { Form, DatePicker, Input, Space, Button } from 'antd'
import moment from 'moment'
import TheButton from "@/components/TheButton";
import GoBack from '@/components/TheGoBack'
import CouponList from "./coupon";
import User from "./uesr";
import _ from "lodash";
import { apiPostCouponTimerAdd, apiPostCouponTimerModify, apiPostTimerCouponPage, apiPostTimerUserPage } from '@/request/couponManagement'

class Detail extends Component {
    constructor(props) {
        super(props)
        this.CouponListRef = React.createRef()
        this.UserListRef = React.createRef()
        this.state = {
            modalStatus: 0,
            title: '创建任务',
            taskId: this.props.match.params.id,
            pushDateTime: new URLSearchParams(props.location.search).get('time'),
            couponList: [],
            userList: []
        }
        this.pageType = new URLSearchParams(props.location.search).get('type')
    }
    sendTimeFormRef = React.createRef()
    idFormRef = React.createRef()

    disabledDate = current => {
        return current && current < moment().startOf('days');
    }

    disabledTime = (date) => {
        let currentDay = moment().date();    //当下的时间
        let currentHours = moment().hours();
        let currentMinutes = moment().minutes();  //设置的时间
        let settingHours = moment(date).hours();
        let settingDay = moment(date).date();
        if (date && settingDay === currentDay && settingHours === currentHours) {
            return {
                disabledHours: () => this.range(0, currentHours - 1),         //设置为当天现在这小时，禁用该小时，该分钟之前的时间
                disabledMinutes: () => this.range(0, currentMinutes +4),
            };
        } else if (date && settingDay === currentDay && settingHours > currentHours) {
            return {
                disabledHours: () => this.range(0, currentHours - 1),      //设置为当天现在这小时之后，只禁用当天该小时之前的时间 
            };
        } else if (date && settingDay === currentDay && settingHours < currentHours) {
            return {
                disabledHours: () => this.range(0, currentHours - 1),      //若先设置了的小时小于当前的，再设置日期为当天，需要禁用当天现在这小时之前的时间和所有的分
                disabledMinutes: () => this.range(0, 59),
            }
        } else if (date && settingDay > currentDay) {
            return {
                disabledHours: () => [],                     //设置为当天之后的日期，则不应有任何时间分钟的限制
                disabledMinutes: () => [],
            }
        }
    }

    range = (start, end) => {
        const result = [];
        for (let i = start; i <= end; i++) {
            result.push(i);
        }
        return result;
    }

    async componentDidMount() {
        if (this.pageType !== 'create') {
            let couponres = await apiPostTimerCouponPage({ pageNo: 1, pageSize: -1, couponTimerCenterId: this.state.taskId })
            let userres = await apiPostTimerUserPage({ pageNo: 1, pageSize: -1, couponTimerCenterId: this.state.taskId })
            this.setState({
                title: '修改任务',
                couponList: couponres.rows.map(item => item.couponInfo),
                userList: userres.rows.map(item => item.memberInfo)
            }, () => {
                this.UserListRef.current.setState({
                    selectedUserSource: this.state.userList
                })
                this.CouponListRef.current.setState({
                    selectedCouponSource: this.state.couponList
                })
            })
            this.sendTimeFormRef.current.setFieldsValue({
                pushDateTime: moment(this.state.pushDateTime),
                couponList: this.state.couponList,
                userList: this.state.userList
            })
        }
    }

    handleIsShowModal(bool, modalStatus = 1) {
        this.CouponListRef.current.openModal()
    }

    handleSubmit = async (value) => {
        value.pushDateTime = moment(value.pushDateTime).format('YYYY-MM-DD HH:mm:ss')
        if(value.pushDateTime > moment(new Date()).format('YYYY-MM-DD HH:mm:ss')){
            if (this.pageType === 'create') {
                // 创建任务
                let res = await apiPostCouponTimerAdd({ ...value })
                if (res.code === 0) {
                    React.$message({
                        type: 'success',
                        content: '定时任务创建成功'
                    })
                    this.props.history.go(-1)
                }
            } else {
                // 修改任务
                value.couponTimerCenterId = this.state.taskId
                let couponList = value.couponList
                let couponListCopy = this.state.couponList
                let filteredCoupon = couponListCopy.filter(item => couponList.findIndex(item2=> item2.couponId === item.couponId) > -1)
                let addcoupon = couponList.filter(item => filteredCoupon.findIndex(item2=> item2.couponId === item.couponId) === -1)
                let deletecoupon = couponListCopy.filter(item => filteredCoupon.findIndex(item2=> item2.couponId === item.couponId) === -1)
                let userList = value.userList
                let userListCopy = this.state.userList
                let filteredUser = userListCopy.filter(item => userList.findIndex(item2=> item2.memberId === item.memberId) > -1)
                let adduser = userList.filter(item => filteredUser.findIndex(item2=> item2.memberId === item.memberId) === -1)
                let deleteruser= userListCopy.filter(item => filteredUser.findIndex(item2=> item2.memberId === item.memberId) === -1)
                value.couponList= addcoupon
                value.userList = adduser
                value.userDeleteIdList = deleteruser
                value.couponDeleteIdList = deletecoupon
                let res = await apiPostCouponTimerModify({...value})
                if(res.code === 0){
                    React.$message({
                        type: 'success',
                        content: '定时任务修改成功'
                    })
                    this.props.history.go(-1)
                }
            }
        }else{
            React.$message({
                type: 'warning',
                content: '发送时间不可小于当前时间'
            })
        }
    }

    validateCouponList = (rule, value, callback) => {
        let list = value ?? []
        if (!list.length) {
            return callback('请选择至少一张有效的优惠券')
        } else {
            return callback()
        }
    }

    validateUserList = (rule, value, callback) => {
        let list = value ?? []
        if (!list.length) {
            return callback('请选择至少一个用户')
        } else {
            return callback()
        }
    }

    onSave() {

    }

    couponListSetData = (e) => {
        console.log(e);
        this.sendTimeFormRef.current.setFieldsValue({
            couponList: e
        })
    }

    userListSetData = (e) => {
        console.log(e);
        this.sendTimeFormRef.current.setFieldsValue({
            userList: e
        })
    }

    render() {
        const { modalStatus, title, couponList, userList } = this.state
        return (
            <div className="p-layout-box">
                <GoBack history={this.props.history} title={title}></GoBack>
                <p style={{ height: 15 }}></p>
                <Form
                    ref={this.sendTimeFormRef}
                    onFinish={(value) => this.handleSubmit(value)}
                    labelCol={{
                        span: 2,
                    }}
                    wrapperCol={{
                        span: 20,
                    }}
                >
                    <Form.Item
                        name="pushDateTime"
                        label="发送时间"
                        rules={[
                            {
                                required: true,
                            }
                        ]}
                    >
                        <DatePicker
                            format="YYYY-MM-DD HH:mm"
                            disabledDate={this.disabledDate}
                            showTime = {{
                                defaultValue: moment(new Date().setMinutes(new Date().getMinutes()+5))
                            }}
                            disabledTime={this.disabledTime}
                            showNow={false}
                        />
                    </Form.Item>
                    <Form.Item
                        label="优惠券"
                        name="couponList"
                        rules={[
                            {
                                required: true,
                                validator: this.validateCouponList
                            }
                        ]}
                    >
                        <TheButton style={{ height: '32px' }} onClick={() => this.handleIsShowModal(true, 0)}>请选择优惠券</TheButton>
                        <CouponList ref={this.CouponListRef} mode={"mode"} getData={couponList} setData={(data) => this.couponListSetData(data)} />
                    </Form.Item>
                    <Form.Item
                        label="发送人群"
                        name="userList"
                        rules={[
                            {
                                required: true,
                                validator: this.validateUserList
                            }
                        ]}
                    >
                        <User ref={this.UserListRef} mode={"mode"} getData={userList} userList={userList} setData={(data) => this.userListSetData(data)} />
                    </Form.Item>
                    <Form.Item
                        wrapperCol={{
                            offset: 2,
                            span: 20,
                        }}
                    >
                        <Space>
                            <Button onClick={() => this.props.history.goBack()}>取消</Button>
                            <Button htmlType="submit" type="primary">保存</Button>
                        </Space>
                    </Form.Item>
                </Form>
            </div>
        )
    }
}

export default Detail
